#include "taster.h"

volatile uint8_t key_state;                                // debounced and inverted key state:
                            		                      // bit = 1: key pressed
volatile uint8_t key_press;                                // key press detect
 
volatile uint8_t key_rpt;

void taster_init(void)
{
	JOYSTICK_INIT_RICHTUNG();
	JOYSTICK_INIT_PULLUP();

	TIMER0_PRESCALER();			// divide by 1024
  	TIMER0_INT_ENABLE();
}

char taste(void)
{
	for(char i=0;i<5;i++)
	{
		if( get_key_press( 1<<i ) || get_key_rpt( 1<<i )) return i;
	}
	return NIX;  
}


uint8_t get_key_press( uint8_t key_mask )
{
  TIMER0_INT_DISABLE();                                        // read and clear atomic !
  key_mask &= key_press;                          // read key(s)
  key_press ^= key_mask;                          // clear key(s)
  TIMER0_INT_ENABLE();
  return key_mask;
}
 
uint8_t get_key_rpt( uint8_t key_mask )
{
  TIMER0_INT_DISABLE();                                         // read and clear atomic !
  key_mask &= key_rpt;                            // read key(s)
  key_rpt ^= key_mask;                            // clear key(s)
  TIMER0_INT_ENABLE();
  return key_mask;
}


ISR(TIMER0_OVF_vect)                            // every 10ms
{
  static uint8_t ct0, ct1, rpt;
  uint8_t i;
 
  TIMER0_REGISTER = (uint8_t)(int16_t)-(F_CPU / 1024 * 10e-3 + 0.5);  // preload for 10ms
 
  i = key_state ^ ~KEY_PIN;                       // key changed ?
  ct0 = ~( ct0 & i );                             // reset or count ct0
  ct1 = ct0 ^ (ct1 & i);                          // reset or count ct1
  i &= ct0 & ct1;                                 // count until roll over ?
  key_state ^= i;                                 // then toggle debounced state
  key_press |= key_state & i;                     // 0->1: key press detect
 
  if( (key_state & REPEAT_MASK) == 0 )            // check repeat function
     rpt = REPEAT_START;                          // start delay
  if( --rpt == 0 ){
    rpt = REPEAT_NEXT;                            // repeat delay
    key_rpt |= key_state & REPEAT_MASK;
  }
  
}

